<?php

/*
Plugin to get data from Google Refine to display edit history on a Google Refine "Project"

This class posts a small JSON string of authorization data to the Google Refine server.
*/

class JSONstore{
    
    public $directoryPath; //full path to the metadata directory
    
    
    const metadataDirectory = "metadata";
    const standardsDirectory = "standards";
    const processesDirectory = "processes";
    
    public function setDirectory($type){
        
        $t_plugin_path = config_get( 'plugin_path' );
         
        if($type == "metadata"){
            $actDir = self::metadataDirectory;
        }
        elseif($type == "standards"){
            $actDir = self::standardsDirectory;
        }
	elseif($type == "processes"){
            $actDir = self::processesDirectory;
        }
        else{
            $actDir = self::metadataDirectory;
        }
        
        $this->directoryPath = $t_plugin_path . 'DataRefine' . DIRECTORY_SEPARATOR . $actDir . DIRECTORY_SEPARATOR;
    }
    
    
    
    
    //just check to see if the file exists, no need to read it
    public function check_file_exists($filename){
        $output = false;
        $filePathName = $this->directoryPath.$filename.".json";
        
        if(file_exists($filePathName)) {
            $output = true;
        }
        return $output;
    }
    
    
    
    public function read_parse_json($filename){
        $output = false;
        $filePathName = $this->directoryPath.$filename.".json";
        
        if(file_exists($filePathName)) {
            
            $rHandle = fopen($filePathName, 'r');
	    if (!$rHandle){
		//nothing
	    }
	    else{
		
		$sData = '';
		while(!feof($rHandle))
		    $sData .= fread($rHandle, filesize($filePathName));
		fclose($rHandle);
		unset($rHandle);
                
                $output = json_decode($sData, true); //convert JSON string to array
	    }
            
        }
        
        return $output;
    }//end function


    //does what it says. saves a json file for later use
    public function save_json($filename, $json){
        
        $filePathName = $this->directoryPath.$filename.".json";
        
	$fp = fopen($filePathName, 'w');
	fwrite($fp, iconv("ISO-8859-7","UTF-8",$json));
        fclose($fp);
    }//end function

    
    
    public function delete_json($filename){
	
	if($this->check_file_exists($filename)){
	    $filePathName = $this->directoryPath.$filename.".json";
	    unlink($filePathName);
	}
    }


}//end class

?>